package logic

import (
	"campus-trade/campusrpc/campusrpc"
	"campus-trade/campusrpc/internal/svc"
	"campus-trade/models/cache"
	"campus-trade/models/mysql"
	"context"
	"fmt"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *campusrpc.LoginRequest) (*campusrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)

	result, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.Mobile).Result()
	if result != in.SendSms {
		return nil, fmt.Errorf("验证码不正确")
	}

	if user.ID == 0 {
		user = mysql.User{
			Mobile:   in.Mobile,
			Password: in.Password,
			Image:    "11111.jpg",
			Name:     fmt.Sprintf("%v:%v", "游客_%d", strconv.Itoa(10000)),
		}
		mysql.DB.Debug().Create(&user)
	} else {
		if in.Password != user.Password {
			return nil, fmt.Errorf("密码错误,请重新输入")
		}
	}

	return &campusrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
